package com.atguigu.gulimail.product.controller;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimail.product.entity.AttrEntity;
import com.atguigu.gulimail.product.entity.ProductAttrValueEntity;
import com.atguigu.gulimail.product.service.AttrService;
import com.atguigu.gulimail.product.service.ProductAttrValueService;
import com.atguigu.gulimail.product.vo.AttrVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 商品属性
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2024-11-03 10:05:39
 */
@RestController
@RequestMapping("product/attr")
public class AttrController {
    @Autowired
    ProductAttrValueService productAttrValueService;
    @Autowired
    private AttrService attrService;

    /**
     * 列表
     */
    @RequestMapping("/{attrType}/list/{catelogId}")
    public R list(@RequestParam Map<String, Object> params, @PathVariable("attrType")
            String attrType, @PathVariable("catelogId") Long catelogId) {
        PageUtils page = attrService.queryPage(params, attrType, catelogId);
        final List<AttrVo> collect =
                page.getList().stream().map(it -> attrService.getAttrVo((AttrEntity) it)).collect(Collectors.toList());
        page.setList(collect);
        return R.ok().put("page", page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{attrId}")
    public R info(@PathVariable("attrId") Long attrId) {
        AttrEntity attr = attrService.getById(attrId);
        final AttrVo attrVo = attrService.getAttrVo(attr);
        return R.ok().put("attr", attrVo);
    }

    @RequestMapping("/base/listforspu/{spuId}")
    public R listforspu(@PathVariable("spuId") Long spuId) {
        List<ProductAttrValueEntity> attrEntities = productAttrValueService.queryAttrBySpuId(spuId);
        return R.ok().put("data", attrEntities);
    }

    @PostMapping("/update/{spuId}")
    public R updateSpu(@PathVariable("spuId") Long spuId,
                       @RequestBody List<ProductAttrValueEntity> items) {
        productAttrValueService.updateSpuAttr(spuId, items);
        return R.ok();
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody AttrVo attr) {
        attrService.save(attr);
        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    public R update(@RequestBody AttrVo attr) {
        attrService.updateById(attr);
        return R.ok();
    }
    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] attrIds) {
        attrService.removeByIds(attrIds);

        return R.ok();
    }

}
